#include "gamewindow.h"
#include "obstacle.h"
#include <QKeyEvent>
#include <QGraphicsTextItem>
#include <QFont>
#include <QBrush>
#include <QImage>

GameWindow::GameWindow(QWidget *parent)
    : QGraphicsView(parent), gameSpeed(5), score(0), gameOver(false)
{
    setFixedSize(800, 400);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 初始化菜单场景
    menuScene = new GameMenu(this);
    connect(menuScene, &GameMenu::startGame, this, &GameWindow::startGame);
    connect(menuScene, &GameMenu::exitGame, this, [](){qApp->quit();});

    setScene(menuScene);

    // 初始化游戏场景
    gameScene = new QGraphicsScene(this);
    gameScene->setSceneRect(0, 0, 800, 400);

}

GameWindow::~GameWindow()
{
    delete gameTimer;
    delete spawnTimer;
    delete elapsedTimer;
    delete scoreTimer;
}

void GameWindow::startGame()
{
    setScene(gameScene);
    initGame();
        // 确保玩家获得焦点（场景切换后可能需要延迟设置）
        QTimer::singleShot(100, [this]() {
            if (player) player->setFocus();
            qDebug() << "Post-start focus:" << (player ? player->hasFocus() : false);
        });
}

void GameWindow::initGame()
{
    gameScene->clear();

    // 设置背景
    QImage bgImage(":/image/D:/game_bg.jpg");
    gameScene->setBackgroundBrush(QBrush(bgImage.scaled(800, 400)));

    // 初始化玩家
    initPlayer();

    // 初始化计时器
    initTimers();

    // 初始化游戏状态
    gameOver = false;
    gameSpeed = 5;
    score = 0;

    // 显示分数
    QGraphicsTextItem *scoreText = new QGraphicsTextItem(QString("分数: %1").arg(score));
    scoreText->setPos(650, 20);
    scoreText->setDefaultTextColor(Qt::white);
    scoreText->setFont(QFont("Arial", 16));
    gameScene->addItem(scoreText);
}

void GameWindow::initPlayer() {
    player = new Player();
    gameScene->addItem(player);

    // 强制焦点设置（延迟100ms确保场景就绪）
    QTimer::singleShot(100, [this]() {
        player->setFocus();
        qDebug() << "强制焦点结果:" << player->hasFocus();
    });
}
void GameWindow::initTimers()
{
    gameTimer = new QTimer(this);
    connect(gameTimer, &QTimer::timeout, this, &GameWindow::update);
    gameTimer->start(16); // ~60 FPS

    spawnTimer = new QTimer(this);
    connect(spawnTimer, &QTimer::timeout, this, &GameWindow::spawnObstacle);
    spawnTimer->start(1000); // 每1秒生成障碍物

    elapsedTimer = new QElapsedTimer();
    elapsedTimer->start();

    scoreTimer = new QElapsedTimer();
    scoreTimer->start();
}

void GameWindow::update()
{
    if(gameOver) return;

    player->update();

    // 更新所有障碍物
    QList<QGraphicsItem*> items = gameScene->items();
    for(QGraphicsItem *item : items) {
        GameObject *obj = dynamic_cast<GameObject*>(item);
        if(obj && obj != player) {
            obj->update();
        }
    }

    // 更新分数 (每100毫秒加1分)
    if(scoreTimer->elapsed() >= 100) {
        score += 1;
        QList<QGraphicsItem*> texts = gameScene->items(QRectF(650, 20, 150, 30));
        for(QGraphicsItem *item : texts) {
            if(QGraphicsTextItem *text = dynamic_cast<QGraphicsTextItem*>(item)) {
                text->setPlainText(QString("分数: %1").arg(score));
                break;
            }
        }
        scoreTimer->restart();
    }

    // 每15秒增加游戏速度
    if(elapsedTimer->elapsed() > 15000) {
        gameSpeed += 1;
        elapsedTimer->restart();
    }

    checkCollisions();
}

void GameWindow::spawnObstacle()
{
    if(gameOver) return;

    // 随机选择行和障碍物类型
    int lane = QRandomGenerator::global()->bounded(3); // 0-2
    int obstacleType = QRandomGenerator::global()->bounded(3); // 0-2

    Obstacle *obstacle = new Obstacle(gameSpeed, lane, obstacleType);
    gameScene->addItem(obstacle);
}

void GameWindow::checkCollisions()
{
    QList<QGraphicsItem*> colliding = player->collidingItems();
    for(QGraphicsItem *item : colliding) {
        if(Obstacle *obstacle = dynamic_cast<Obstacle*>(item)) {
            // 检查是否在同一行
            if(obstacle->getLane() == player->getLane()) {
                gameOver = true;
                showScore();
                break;
            }
        }
    }
}

void GameWindow::showScore()
{
    cleanGame();

    scoreScene = new GameScore(score, this);
    connect(scoreScene, &GameScore::restartGame, this, &GameWindow::startGame);
    connect(scoreScene, &GameScore::returnToMenu, this, &GameWindow::returnToMenu);

    setScene(scoreScene);
}

void GameWindow::returnToMenu()
{
    cleanGame();
    setScene(menuScene);
}

void GameWindow::cleanGame()
{
    gameTimer->stop();
    spawnTimer->stop();

    QList<QGraphicsItem*> items = gameScene->items();
    for(QGraphicsItem *item : items) {
        gameScene->removeItem(item);
        delete item;
    }

    delete scoreTimer;
    delete elapsedTimer;
    delete gameTimer;
    delete spawnTimer;
}

void GameWindow::keyPressEvent(QKeyEvent *event)
{
    qDebug()<<"Key pressed in Player:"<<event->key();
    if(event->key() == Qt::Key_Escape && scene() == gameScene) {
        // 暂停游戏
        if(gameTimer->isActive()) {
            gameTimer->stop();
            spawnTimer->stop();
        } else {
            gameTimer->start();
            spawnTimer->start();
        }
    } else {
        QGraphicsView::keyPressEvent(event);
    }
}
